#!/usr/bin/python
# coding:utf-8
__author__ = 'golsee'
__createday__ = '2015-03-10'

import os
import logging
import tarfile
import urlparse
import sys

required = ['wget', 'make', 'gcc', 'gcc-c++', 'zlib', 'zlib-devel', 'libxml2-devel', 'pcre-devel']
DIRNAME = os.path.abspath(os.path.dirname(__file__))


def yum_install(required):
    for r in required:
        os.system('yum install -y %s' % r)


# 下载
def download(url):
    filename = urlparse.urlparse(url).path.split('/')[-1]
    print '开始下载 %s' % filename
    if not os.path.exists('tmp'):
        os.makedirs('tmp')
    if not os.path.exists('tmp/%s' % filename):
        os.system('cd tmp/ && wget %s' % url)
    print '下载成功'
    return filename


#: 升级python
def update_python():
    if sys.version_info.major == 2 and sys.version_info.minor == 7:
        logging.info('PYTHON已是最新，无需更新')
    else:
        logging.info('开始更新PYTHON...')
        filename = download('https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tgz')
        dirs = _extract('tmp/%s' % filename)
        os.system('cd %s && ./configure --prefix=/usr/local/python27' % dirs)
        os.system('cd %s && pwd && make && make install' % dirs)
        logging.info('编译成功,设置环境...')
        if os.path.exists('/usr/bin/python'):
            os.remove('/usr/bin/python')
        if os.path.exists('/usr/local/bin/python'):
            os.remove('/usr/local/bin/python')
        os.system('ln -s /usr/local/python27/bin/python /usr/bin/')
        os.system('ln -s /usr/local/python27/bin/python /usr/local/bin/')
        download(
            'https://pypi.python.org/packages/source/s/setuptools/setuptools-15.0.tar.gz#md5=2a6b2901b6c265d682139345849cbf03')
        dirs = _extract('tmp/setuptools-15.0.tar.gz')
        os.system('cd %s && python setup.py install' % dirs)
        if os.path.exists('/usr/local/bin/easy_install'):
            os.remove('/usr/local/bin/easy_install')
        os.system('ln -s /usr/local/python27/bin/easy_install /usr/local/bin/')
        os.system('easy_install pip')
        os.system('ln -s /usr/local/python27/bin/pip /usr/local/bin/')
        logging.info('PYTHON安装完成...')


#: 安装nginx
def install_nginx():
    logging.info('开始安装nginx...')
    filename = download('wget http://nginx.org/download/nginx-1.6.2.tar.gz')
    dirs = _extract('tmp/%s' % filename)
    os.system(
        'cd %s && ./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_gzip_static_module --with-http_gunzip_module  --http-uwsgi-temp-path=/tmp/' %
        dirs)
    os.system('cd %s && pwd && make && make install' % dirs)
    os.system('cp tmp/nginx /etc/init.d/ && chmod u+x /etc/init.d/nginx')
    os.system('chkconfig --add nginx && chkconfig nginx on')
    os.system('service nginx start')


def _extract(filename):
    logging.info('解压%s...' % filename)
    import tarfile

    filenames = os.path.splitext(filename)
    realfilename = filenames[0]
    if '.tgz' in filenames or '.gz' in filenames:
        file = tarfile.open(filename)
        names = file.getnames()
        for name in names:
            file.extract(name, 'tmp/')
        file.close()
    tmp = os.path.splitext(filenames[0])
    if tmp[1] == '.tar':
        realfilename = tmp[0]

    return '%s/tmp/%s' % (DIRNAME, realfilename.split('/')[-1])


#: 安装uwsgi
def install_uwsgi():
    os.system('pip install --upgrade uwsgi')
    os.system('ln -s /usr/local/python27/bin/uwsgi /usr/bin/')
    os.system('cp tmp/uwsgid /etc/init.d/ && chmod u+x /etc/init.d/uwsgid')
    os.system('chkconfig --add uwsgid && chkconfig uwsgid on')
    os.system('service uwsgid start')


#: 安裝redis
def install_redis():
    logging.info('开始安裝redis...')
    filename = download('http://download.redis.io/releases/redis-3.0.0.tar.gz')
    dirs = _extract('tmp/%s' % filename)
    os.system('cd %s && pwd && make && make install' % dirs)
    os.system('cd %s && cp -f redis.conf /etc' % dirs)
    os.system('cp tmp/redis /etc/init.d/ && chmod u+x /etc/init.d/redis')
    os.system('chkconfig --add redis && chkconfig redis on')
    os.system('service redis start')


if __name__ == '__main__':
    yum_install(required)
    update_python()
    install_redis()
    install_uwsgi()
    install_nginx()